package com.lx.mvc;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * @ClassName: DispatcherServlet
 * @Description:
 * @Date Created in  2021-07-03 9:05
 * @Modified By:
 * @Author: 零巽
 */
public class DispatcherServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        String path = config.getInitParameter("contentConfigLocation");//xml里配置的初始化参数名
        InputStream inputStream = DispatcherServlet.class.getClassLoader().getResourceAsStream(path);
//        加载配置文件方法，移至HandlerMapping
//        Properties properties = new Properties();
//        try {
//            properties.load(inputStream);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        HandlerMapping.load(inputStream);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        HandlerMapping.MACMapping macMapping = HandlerMapping.get(requestURI);
        if (macMapping == null) {
            resp.sendError(404,"自定义MVC：映射地址不存在"+requestURI);
            return;
        }
        Object obj = macMapping.getObject();
        Method method = macMapping.getMethod();
        ResponseType type = macMapping.getType();
        Object result =null;
        try {
            result = method.invoke(obj, req, resp);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        switch (type) {
            case TEXT:
                resp.getWriter().write((String)result);
                break;
            case VIEW:
                resp.sendRedirect((String)result);
                break;
        }
    }
}
